package com.gp.pj.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.gp.pj.entity.User;
import com.gp.pj.mapper.UserMapper;
import com.gp.pj.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gp.pj.utils.JWTUtils;
import com.gp.pj.vo.UserVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static com.gp.pj.utils.MD5Utils.encodePwd;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Chloe
 * @since 2020-12-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public Map<String, UserVo> login(String userName, String password){
        Integer num = userMapper.checkUser(userName);
        System.out.println(num);
        if(num==null){
            throw new NullPointerException("没有该用户信息,请联系管理员");
        }

        try{
            password = encodePwd(password);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(password);
        Map<String,UserVo> map = userMapper.login(userName,password);
        if(map!=null){
            return map;
        }
        throw new NullPointerException("账号或密码错误");
    }

    @Override
    public JSONObject getUserInfo(String token) {
        DecodedJWT decToken = JWTUtils.verifyToekn(token);
        String userId = decToken.getClaim("userId").asString();
        List<UserVo> userInfo = userMapper.getUserInfo(userId);
        if(null == userInfo || userInfo.size() ==0 ){
            throw new NullPointerException("没有该用户的权限信息,请先设置权限!");
        }else{
            JSONArray access = new JSONArray();
            userInfo.forEach(item -> {
                access.add(item.getAccesses());
            });
            JSONObject data = new JSONObject();
            data.put("userId",userId);
            data.put("userName",decToken.getClaim("userName").asString());
            data.put("access",access);
            return data;
        }
    }

    @Override
    public JSONArray getUserList() {
        List<UserVo> userList = userMapper.getUserList();
        JSONArray data = new JSONArray();
        //处理accesses中的结果集
        userList.forEach(item -> {
            if(item.getAccesses()!=null){
                String[] accessList = item.getAccesses().split(",");
                JSONArray access = new JSONArray();
                for (String accesses :accessList) {
                    access.add(accesses);
                }
                item.setAccess(access);
            }else{
                JSONArray access = new JSONArray();
                item.setAccess(access);
            }
            data.add(item);
        });
        return data;
    }

}
